const cloud = require('@cloudbase/node-sdk');

const app = cloud.init({
  env: cloud.SYMBOL_CURRENT_ENV
});

const db = app.database();
const _ = db.command;

exports.main = async (event, context) => {
  try {
    const { page = 1, pageSize = 10, category, artist } = event;
    
    let query = {};
    if (category) {
      query.category = category;
    }
    if (artist) {
      query.artistId = artist;
    }

    const countResult = await db.collection('artworks')
      .where(query)
      .count();

    const total = countResult.total;

    const list = await db.collection('artworks')
      .where(query)
      .skip((page - 1) * pageSize)
      .limit(pageSize)
      .get();

    return {
      code: 0,
      data: {
        list: list.data,
        total,
        page,
        pageSize,
        totalPages: Math.ceil(total / pageSize)
      },
      message: 'success'
    };
  } catch (error) {
    return {
      code: 1,
      message: error.message
    };
  }
};